package com.nf.controller.login;

import com.google.gson.Gson;
import com.nf.controller.BaseServlet;
import com.nf.dao.AdminInfoDao;
import com.nf.dao.UserInfoDao;
import com.nf.dao.impl.AdminInfoDaoImpl;
import com.nf.dao.impl.UserInfoDaoImpl;
import com.nf.entity.AdminInfo;
import com.nf.entity.UserInfo;
import com.nf.util.GsonUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 编写servle，实现登录
 */
@WebServlet("/api/LoginServlet.do")
public class LoginServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取数据
        String name=req.getParameter("name");
        String pass=req.getParameter("pass");
        String code=req.getParameter("code");

        System.out.println(code);
        // 获取服务器产生的验证码
        HttpSession session = req.getSession();
        // 会话ID
        // System.out.println(session.getId());
        // 默认的session key为com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY
        // 根据需要，可以重新配置
        String serverCode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        // String serverCode = (String) req.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        System.out.println(serverCode);


        UserInfoDao userDao=new UserInfoDaoImpl();
        AdminInfoDao adminDao=new AdminInfoDaoImpl();

        UserInfo user=userDao.findUser(name,pass);
        AdminInfo admin=adminDao.findAdmin(name,pass);

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        // 忽略大小写比较验证码（验证客户输入的验证码是否正确）
//        if(code.equalsIgnoreCase(serverCode)){
            if(user!=null){
                out.print(new Gson().toJson(successJson(user)));
            }else if(admin!=null){
                out.print(new Gson().toJson(successJson(admin)));
            }else {
                out.print(new Gson().toJson(errorJson("账号或密码错误")));
            }
//        }else {
//            out.print(new Gson().toJson(errorJson("请输入正确的验证码")));
//        }

        out.flush();
        out.close();

    }
}
